<template>
  <el-container class="main_con" >
    <div class="edit_con">
      <div class="edit_title">{{pageName}}</div>
      <div class="edit_content">
        <el-form size="medium" label-width="100px" ref="itemForm" :model="obj" :rules="itemRules"  class="edit_form" style="width:100%">  

          <el-form-item label="发件人手机" prop="mobile">
            <el-input placeholder="请输入手机号" v-model="obj.mobile" :style="width360"></el-input>
          </el-form-item>

          <el-form-item label="发件人电话">
            <el-input placeholder="请输入电话号码" v-model="obj.tel" :style="width360"></el-input>
          </el-form-item>

          <el-form-item label="发件人姓名" prop="name">
            <el-input placeholder="请输入发件人" v-model="obj.name" :style="width360"></el-input>
          </el-form-item>

          <!-- :required="obj.shipper_code == 2" -->
          <el-form-item label="邮编">
            <el-input placeholder="请输入发件人邮编" v-model="obj.post_code" :style="width360"></el-input>
          </el-form-item>

          <el-form-item label="发货地区" prop="districtSelected">
            <el-cascader
              style="width:300px;"
              :options="options"
              v-model="obj.districtSelected"
              @change="districtSelect">
            </el-cascader>
            
          </el-form-item>

          <el-form-item label="发货地址" prop="address">
            <el-input placeholder="请输入具体地址" v-model="obj.address" :style="width360"></el-input>
          </el-form-item>

          <el-form-item label="快递编号" prop="shipper_code">
            <el-select v-model="obj.shipper_code" filterable placeholder="请选择物流">
              <el-option
                v-for="item in expressList"
                :key="item.id"
                :label="item.name"
                :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>

          <el-divider></el-divider>

          <el-form-item label="运输方式">
            <el-radio-group v-model="obj.trans_type">
              <el-radio :label="1">陆运</el-radio>
              <el-radio :label="2">空运</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="支付方式">
            <el-select v-model="obj.pay_type" placeholder="请选择支付方式">
              <el-option label="现付" :value="1"></el-option>
              <el-option label="到付" :value="2"></el-option>
              <el-option label="月结" :value="3"></el-option>
              <el-option label="第三方支付(仅SF支持)" :value="4"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="快递类型">
            <el-radio-group v-model="obj.exp_type">
              <el-radio :label="1">标准快件</el-radio> 
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否要求回单">
            <el-radio-group v-model="obj.is_return_sign_bill">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否要求回单">
            <el-input :style="width360" placeholder="签回单操作要求(如：签名、盖章、身份证复印件等)" type="textarea" rows="2" v-model="obj.operate_require"></el-input>
          </el-form-item>

          <el-form-item label="上门揽件">
            <el-radio-group v-model="obj.is_notice">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="订阅短信">
            <el-radio-group v-model="obj.is_send_message">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-divider></el-divider>

          <el-form-item label="客户账号">
            <el-input :style="width360" placeholder="请输入客户账号" v-model="obj.customer_name"></el-input>
          </el-form-item>

          <el-form-item label="客户密码">
            <el-input type="password" :style="width360" placeholder="请输入客户密码" v-model="obj.customer_pwd"></el-input>
          </el-form-item>

          <el-form-item label="发送站点">
            <el-input :style="width360" placeholder="请输入发送站点" v-model="obj.send_site"></el-input>
          </el-form-item>

          <el-form-item label="派遣工作人员">
            <el-input :style="width360" placeholder="请输入派遣工作人员" v-model="obj.send_staff"></el-input>
          </el-form-item>

          <el-form-item label="月份代码">
            <el-input :style="width360" placeholder="请输入月份代码" v-model="obj.month_code"></el-input>
          </el-form-item>


          <el-form-item label="发货仓编码">
            <el-input :style="width360" placeholder="请输入发货仓编码" v-model="obj.ware_house_id"></el-input>
          </el-form-item>

          <!-- <el-form-item label="状态">
            <el-radio-group v-model="obj.status">
              <el-radio :label="0">未启用</el-radio>
              <el-radio :label="1">正常</el-radio>
              <el-radio :label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item> -->
          
        </el-form>
      </div>
      <div class="edit_footer">
        <el-button v-has size="medium" type="primary" @click="saveData">保存数据</el-button>
      </div>
    </div>
  </el-container>
</template>

<script>
import {regionData,CodeToText,TextToCode} from 'element-china-area-data'
import {
  addEBTemplate,
  editEBTemplate,
  getEBTemplate
} from '@/api/shop/print';
import { getexpress } from '@/api/shop/freight';

export default {
  data(){
    //校验号码
    let validateMobile = (rule, value, callback) => {
      if (!(/^1[23456789]\d{9}$/.test(value))) {
        callback(new Error('手机号码有误，请重填'))
      } else {
        callback()
      };
    };

    return {
      showMap:false,
      obj:{
        district:'',
        districtSelected: [],

        province_name:'',
        city_name:'',
        exp_area_name:'',
        address:'',
        shipper_code:'',//快递公司编号(SF,EMS)
        mobile:'',
        tel:'',
        name:'',
        post_code:'',
        trans_type:1,//运输方式 1- 陆运 2- 空运 不填默认为1 
        pay_type:1,//邮费支付方式:1-现付，2-到付，3-月结，4-第三方支付(仅SF支持)
        exp_type:1,//快递类型：1-标准快件
        is_return_sign_bill:1,//是否要求签回单
        operate_require:'',//签回单操作要求(如：签名、盖章、身份证复印件等)
        is_notice:1,//是否通知快递员上门揽件
        is_send_message:1,//是否订阅短信
        customer_name:'',//客户账号
        customer_pwd:'',//客户密码
        send_site:'',//发送站点
        send_staff:'',//派遣工作人员
        month_code:'',//月份代码
        ware_house_id:''//发货仓编码
      },
      expressList:[],
      pageIsEdit:0,//0->新增,1->编辑,2->通过申请
      pageName:'新增模板',
      isLoading:false,
      options: regionData,
      itemRules: {
          mobile: [{
            required: true,
            validator: validateMobile
          }],
          name: [{
            required: true,
            message: '请输入发件人'
          }],
          shipper_code: [{
            required: true,
            message: '快递公司编号必须选择'
          }],
          post_code: [{
            required: true,
            message: '请输入邮编'
          }],
          address: [{
            required: true,
            message: '请输入具体地址'
          }],
          districtSelected: [{
            type:'array',
            required: true,
            message:'请选择所在区域'
          }]
        }
    }
  },
  components: {},
 
  created(){
    this.getExpressAll();
    //获取路由参数(编辑时使用)
    if(this.$route.query.id){
      //编辑页面
      this.pageIsEdit = 1;
      this.pageName = '编辑模板'; 
      this.$route.meta.title = '编辑模板';
      this.getTemplate(this.$route.query.id);
    }else{
      this.pageIsEdit = 0;
      this.pageName = '新增模板'; 
      this.$route.meta.title = '新增模板';
      //this._obj = Object.assign({},this.obj);
    };

  },
  computed:{
    width360(){
      return 'width:360px;'
    }
  },
  methods:{
    //获取所有快递
    getExpressAll(){
      this.isLoading = true;
      getexpress().then(res => {
        this.isLoading = false;
        this.expressList = res.msg;
      });
    },
    //获取基本数据
    getTemplate(id){
      this.isLoading = true;
      getEBTemplate(id).then(res => {
        this.isLoading = false;
        let o = res.msg;
        //  district:'',
        //districtSelected: [],

        //处理所在区域
        let _d = [];
        
        //拼接所在区域选择数组
        _d[0] = TextToCode[o.province_name].code;
        _d[1] = TextToCode[o.province_name][o.city_name].code;
        _d[2] = TextToCode[o.province_name][o.city_name][o.exp_area_name].code;
        o.districtSelected = _d;
        o.district = o.province_name + ',' + o.city_name + ',' + o.exp_area_name;

        //赋值
        this.obj = {...o};

      }).catch(e => {
        this.isLoading = false;
      })
    },

    //获取通过申请页面基础数据
    getMerchantApply(id){
      this.isLoading = true;
      getMerchantApply(id).then(res => {
        this.isLoading = false;
        let o = res.msg;

        //处理数据,status字段不处理
        //处理所在区域
        let _d = [];
        let _t;
        if(o.district.indexOf(',') > -1){
          _t = o.district.split(',');
        }else{
          _t = o.district.split(' ');
        };
        //拼接所在区域选择数组
        _d[0] = TextToCode[_t[0]].code;
        _d[1] = TextToCode[_t[0]][_t[1]].code;
        _d[2] = TextToCode[_t[0]][_t[1]][_t[2]].code;
        o.districtSelected = _d;

        //补全整理字段
        delete o.id;
        o.business_license = '';
        o.tpye = 1;
        o.indate = '';
        o.status = 0;
        o.apply_id = id;

        //赋值
        this.obj = Object.assign({},o);
      });
    },
    //选择用户
    selectUserId(item){
      this.obj.user_id = item.id;
      this.obj.mobile = item.mobile;

      this.$refs.shForm.validateField('mobile');
    },
    //选择是否永久有效
    changeInDate(flag){
      //console.log(val)
      if(flag){
        //永久有效
        this.obj.indate = '';
      }else{
        //no code
      };
      this.$refs.shForm.validateField('indate');
    },
    //获取图片
    getImage(val) {
      this.obj.business_license = val;
    },
    //级联选择区域
    districtSelect (value) {
      let s = '';
      value.forEach(e => {
        s += CodeToText[e] + ',';
      });
      s = s.substring(0,s.length - 1)
      //对象赋值
      this.obj.district = s;
    },
    //保存数据
    saveData(){
      let _data = {...this.obj}
      this.$refs.itemForm.validate(valid => {
        if (valid) {
          //校验数据
          if(_data.mobile == '' && _data.tel == ''){
            this.$alert('发件人手机与电话号码不能同时为空');
            return false;
          };

          if(_data.shipper_code == 'EMS' && _data.post_code == ''){
            this.$alert('快递公司为邮政EMS时,邮编必须填写');
            return false;
          };

          //处理数据
          _data.province_name = _data.district.split(',')[0];
          _data.city_name = _data.district.split(',')[1];
          _data.exp_area_name = _data.district.split(',')[2];

          //删除字段
          delete _data.district;
          delete _data.districtSelected;

          //保存数据
          this.isLoading = true;
          switch(this.pageIsEdit){
            case 0:
              //新增
              addEBTemplate(_data).then(res => {
                this.isLoading = false;
                this.$router.push('/print/template/electronics');
              }).catch(e => {
                this.isLoading = false;
              });
              break;
            case 1:
              //编辑
              delete _data.status_text;
              //_data.test = 1;
              editEBTemplate(_data).then(res => {
                this.isLoading = false;
                this.$router.push('/print/template/electronics');
              }).catch(e => {
                this.isLoading = false;
              });
              break;
            default:
              //no code
              break;
          };            
        } else {
          //console.log('error')
          return false
        }
      });

      
    },
    //关闭坐标选择器窗口
    closeMap(e){
      this.showMap = false;
      this.obj.longitude = e[0];
      this.obj.latitude = e[1];
    }
  }
}
</script>

<style lang="scss" scoped></style>